const redis = require('redis')

//从env中获取配置
let { REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD } = process.env
const host = REDIS_HOST
const port = REDIS_PORT
const db = REDIS_DB
const password = REDIS_PASSWORD

let client = redis.createClient({
  host,
  port,
  db,
  password
})

client.on('error', function(err) {
  console.error('redis报错，错误信息：', err)
})

Object.assign(client, {
  /**
   * 创建同步的get方法
   * @param {*} key
   */
  asyncGet(key) {
    return new Promise((resolve, reject) => {
      client.get(key, (err, res) => {
        if (err) {
          reject(err)
        } else {
          resolve(res)
        }
      })
    })
  },
  /**
   * 创建同步的set方法
   * @param {*} key
   */
  asyncSet(key, value) {
    return new Promise((resolve, reject) => {
      client.set(key, value, (err, res) => {
        if (err) {
          reject(err)
        } else {
          resolve(res)
        }
      })
    })
  }
})

module.exports = client
// export default client
